@extends('template.layout')

@section('resources')
    <script src={{asset('/js/parallax/parallax.min.js')}}></script>
    <title>订单中心 | 专注5-12周岁儿童在线教学，严选美国外教，游戏化教学｜久趣英语</title>
@stop


@section('content')
    <div class="scroll-point"></div>
    <div class="page-content">
        <div class="page-section">

            <div class="header " style="width:900px;margin:0 auto;position: relative">
                <a onclick="window.history.back()"><div class="left-arrow-icon"></div></a>
                <span>购买课程</span>
            </div>


            <div style="width:1000px;margin:0 auto;">
                <div class="account" id="account">
                    <span class="">当前账号</span>
                    <span class="phone" id="currentAccount">  </span>

                    <div class="change-account" id="changeAccount">更换账户</div>

                </div>
            <div class="progress">

                <div class="p-line " id="line1">
                    <div></div>
                </div>
                <div class="p-circle " id="circle1">
                    1
                    <span>核对订单</span>
                </div>


                <div class="p-line " id="line2">
                    <div class="move-forward"></div>
                </div>
                <div class="p-circle" id="circle2">2
                    <span>订单状态</span>
                </div>

                <div class="p-line" id="line3">
                    <div></div>
                </div>
                <div class="p-circle" id="circle3">3
                    <span>软件下载</span>
                </div>

                <div class="p-line" id="line4">
                    <div></div>
                </div>
            </div>
            </div>

            <div class="order-step active-step" id="step1">

                <div class="order-detail">

                    <div class="divider">
                        <div class="text"> 课程详情</div>
                        <div class="line"></div>
                    </div>

                    <div class="detail-table">
                        <div class="o-d-item">
                            <span>开班时间</span>
                            <span>上课频率</span>
                            <span>班级模式</span>
                            <span>会员卡</span>
                            <span>价格</span>
                        </div>

                        <div class="o-d-value">
                            <span>{{$products[$pId]['openTime']}}</span>
                            <span>{{$products[$pId]['suggestion']}}</span>
                            <span>精品2、4人班</span>
                            <span>{{$products[$pId]['_gift']}}</span>
                            <span class="highlight">¥{{$products[$pId]['total']}}</span>
                        </div>

                        <div class="order-total">
                            <span>应付金额：</span>
                            <span class="total">¥{{$products[$pId]['total']}}</span>
                        </div>
                    </div>
                </div>


                <div class="pay-method">

                    {{--<input type="hidden" id="payMethod" value="alipay"/>--}}
                    <div class="divider">
                        <div class="text">付款方式</div>
                        <div class="line"></div>
                    </div>


                    <div class="method-list">

                        <div class="method-item selected" data-field="alipay">
                            {{--<div class="option selected-option" data-field="alipay"></div>--}}
                            <div class="alipay"></div>
                            <span>支付宝</span>
                            <div class="triangle">
                                <div class="ok-white-icon select"></div>
                            </div>
                        </div>

                    </div>

                </div>


                <div class="submit-order" id="submitOrder">
                    {{$pId != 1 && $limit && $limit['day'] > 0 ? '待开放' : '立即购买'}}
                </div>
                <div class="buy-tip" style="display: {{$limit && $limit['day'] > 0 ? 'block' : 'none'}}; visibility: {{$pId == 1 ? 'hidden' : 'visible'}}">{{$limit['next']}} 开放报名</div>

            </div>

            <div class="order-step" id="step2" style="height:400px;">

                <div class="confirm-payment" id="confirmPay">
                    <p>请在打开的支付页面完成支付, 支付完成前不要关闭窗口</p>
                    <div class="pay-result-btns">
                        <div class="s-pay" id="sPay">支付完成</div>
                        <div class="f-pay" id="fPay">支付失败</div>
                    </div>
                </div>


                <div class="error-pay" id="errorPay">
                    <p>订单尚未支付成功,请在支付页重新支付或者重新提交订单</p>
                    <div class="pay-result-btns">
                        <div class="s-pay" id="rePay">重新支付</div>
                        <div class="f-pay" id="reOrder">重新提交订单</div>
                    </div>
                </div>
            </div>

            <div class="order-step" id="step3">

                <div class="soft-download">
                    <p>付款完毕, 下载软件登录后就能上课啦!</p>
                    <a href="http://gstatic.97kid.com/shell/2.0.0/setup.student.exe" >
                        <div class="item">
                            <div class="win-big-icon"></div>
                            <span>WINDOWS 下载</span>
                        </div>
                    </a>

                    <a href="http://gstatic.97kid.com/shell/2.0.0/setup.student.dmg">
                        <div class="item">
                            <div class="mac-big-icon"></div>
                            <span>MAC 下载</span>
                        </div>
                    </a>

                    <a target="_blank" href="https://itunes.apple.com/cn/app/jiu-qu-ying-yu/id1043496499">
                        <div class="item">
                            <div class="pad-big-icon"></div>
                            <span>IPAD 下载</span>
                        </div>
                    </a>
                </div>
            </div>

        </div>

    </div>

    <div class="recom-mask" id="recomMask">
        <div class="recom-box">
            <h1>您已经购买过¥100/4课时了，建议您购买以下课程</h1>

            <div class="recom-lesson-plan">

                @foreach($products as $product)
                    @if($product['p_id']  != $pId)
                    <a class="recom-plan-detail" href="/order/{{$product['p_id']}}">
                        <div>
                            <div class="fee">
                                ¥ <span class="money">{{$product['total']}}</span> / {{$products[$pId]['_gift']}}
                            </div>

                            <div class="schedule">
                                <span>{{$product['refundDate']}}</span>
                                <span>{{$product['suggestion']}}</span>
                                <span>{{$product['extra']}}</span>
                            </div>

                            <div class="buy-now">
                                {{$product['p_id'] != 1 && $limit && $limit['day'] > 0 ? '待开放' : '立即购买'}}
                            </div>
                            <div class="buy-tip" style="display: {{$limit && $limit['day'] > 0 ? 'block' : 'none'}}; visibility: {{$product['p_id'] == 1 ? 'hidden' : 'visible'}}">{{$limit['next']}} 开放报名</div>
                        </div>
                    </a>
                    @endif
                @endforeach

            </div>
        </div>
    </div>

    @include('partial.loginAndRegister')
@stop

@section('script')

    <script>


        $(document).ready(function () {

            //进入第一步
            goStep1();

            //账单号
            var billNo = '';

            //检查是否已经登录
            login();

            //更换账户
            $('#changeAccount').click(function(){
                $('.login-mask').fadeIn();
            })

            //选择支付方式
            $('.method-item').click(function () {
                $(this).toggleClass('selected');
                $(this).siblings('.method-item').removeClass('selected');
            });


            $('#hBuyBtn').click(function () {
                toastAlert('请先完成当前订单',2)
            });

            @if($pId == 1 || ($limit && $limit['day'] == 0))
              // 提交订单
              $('#submitOrder').click(function () {

                //检查是否已经登录
                if(!login()) {
                  return false;
                }

                //检查是否选择支付方式
                var payMethod = checkPaymethod();

                if(payMethod === '')
                  return false;

                // 检查user id
                var userId;
                if (JSON.parse(localStorage.getItem("userId")) === null) {
                  userId = checkUserId();
                } else {
                  userId = localStorage.getItem("userId");
                }

                // 提交订单

                submitOrder(payMethod,userId);

              });
            @endif


            //检查支付状态
            $('#sPay, #fPay').click(function () {

                //验证订单是否已经支付
                $.ajax({
                    type: 'GET',
                    async: true,
                    url: '/bills/'+billNo,
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
                        '_token': $('meta[name="_token"]').attr('content'),
                        'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem("token")).access_token
                    },
                    success: function (data) {

                        if (typeof(data.status) !== 'undefined' && data.status === 20) {
                            //进入第三步
                            goStep3();

                        } else {
                            $('#confirmPay').hide();
                            $('#errorPay').fadeIn();
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastAlert(errorThrown, 2);
                    }
                })
            });


            //重新支付
            $('#rePay').click(function() {
                $('#errorPay').hide();
                $('#confirmPay').fadeIn();

            })

            // 退回到下单,重新下单
            $('#reOrder').click(function () {
                $('#confirmPay').show();
                $('#errorPay').hide();
                $('#step1').fadeIn().siblings('.order-step').hide();


                $('#circle2').removeClass('in-s');
                setTimeout(function () {
                    $('#line2').find('div').animate({width: 0}, 1000, 'swing');
                }, 300);
            });

            function getUrlPara(para, url) {
                var reg = new RegExp("(^|&)" + para + "=([^&]*)(&|$)");
                var r = url.match(reg);
                if (r !== null) return decodeURI(r[2]);
                return null;
            }

            //进入第一步
            function goStep1() {
                //第一步
                $('#line1').find('div').animate({width: 120}, 500, 'swing');
                setTimeout(function () {
                    $('#circle1').addClass('in-s');
                }, 500);
            }

            //进入第二步
            function goStep2() {
                $('#step2').fadeIn().siblings('.order-step').hide();
                $('html,body').animate({scrollTop: '0px'}, 300);

                $('#line2').find('div').animate({width: 120}, 500, 'swing');
                setTimeout(function () {
                    $('#circle2').addClass('in-s');
                }, 500);
            }

            //进入第三步
            function goStep3() {

                $('#step3').fadeIn().siblings('.order-step').hide();
                $('html,body').animate({scrollTop: '0px'}, 300);

                $('#line3').find('div').animate({width: 120}, 500, 'swing');
                setTimeout(function () {
                    $('#circle3').addClass('in-s');
                }, 500);

                setTimeout(function () {
                    $('#line4').find('div').animate({width: 120}, 500, 'swing');
                }, 1000);

            }

            //唤起登录窗口
            function login() {
                if (JSON.parse(localStorage.getItem("token")) === null ||
                    (JSON.parse(localStorage.getItem("token")) !== null &&
                    JSON.parse(localStorage.getItem("token")).expires_in < Date.now())) {
                    $('.login-mask').fadeIn();
                    return false;
                } else {

                    if( typeof (localStorage.getItem('mobile'))!== undefined && localStorage.getItem('mobile') !== null) {
                        $('#account').show();
                        $('#currentAccount').text(localStorage.getItem('mobile'));
                    }

                }
                return true;
            }

            //检查支付方式
            function checkPaymethod() {

                var payMethod = '';
                $('.method-item').each(function () {
                    if ($(this).hasClass('selected')) {
                        payMethod =  $(this).attr('data-field');
                    }
                })

                if(payMethod === '')
                    toastAlert('请选择付款方式', 2);


                return payMethod;

            }

            //获取user id
            function checkUserId() {
                var user_id = '';
                $.ajax({
                    type: 'POST',
                    async: false,
                    url: ' /users/me',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
                        '_token': $('meta[name="_token"]').attr('content'),
                        'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem("token")).access_token
                    },
                    success: function (data) {
                        if (typeof(data.code) !== "undefined") {
                            toastAlert(data.message || '获取信息失败，请重试', 2);
                        } else {
                            localStorage.setItem("userId", data.id);
                            user_id = data.id;
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastAlert(errorThrown, 2);
                    }
                });
                return user_id;
            }

            // 提交订单
            function submitOrder(payMethod,userId) {
                var success = false;
                var responseData = '';

                $.ajax({
                    type: 'POST',
                    async: false,
                    url: ' /bills',
                    dataType: 'json',
                    data: {
                      cashAmount: "{{$products[$pId]['total']}}",
                      productType: 0,
                      productId: '{{$pId}}',
                      payChannel: 'alipay',
                      tradeType: 'directPay',
                      returnUrl: window.location.protocol+'//'+window.location.host+'/verifypayment',
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
                        '_token': $('meta[name="_token"]').attr('content'),
                        'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem("token")).access_token
                    },
                    success: function (data) {
                        if (typeof(data.code) !== "undefined") {
                            if (data.code == 'recharge.level.not.applicable.to.user') {
                              toastAlert('你已购买过体验课', 2);
                            } else {
                              toastAlert(data.message, 2);
                            }
                        } else {
                            if (typeof(data.status) !== 'undefined' && data.status === 'success') {

                                success = true;
                                responseData = data;
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastAlert('订单创建失败', 2);
                    }
                });

                if(success) {
                    //进入第二部
                    goStep2();
                    billNo = getUrlPara('out_trade_no', responseData.url);
                    setTimeout(openPayPage(responseData.url), 700)
                }
            }

            //打开支付页面
            function openPayPage(url) {
                var el = document.createElement("a");
                document.body.appendChild(el);
                el.href = url;
                el.target = "_blank";
                el.click();
                document.body.removeChild(el);
            }
        })
    </script>

@stop



